package com.ketangpai.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ketangpai.admin.common.PageResult;
import com.ketangpai.admin.dao.StuWorkDao;
import com.ketangpai.admin.dao.UserCourseDao;
import com.ketangpai.admin.dao.UserDao;
import com.ketangpai.admin.dao.WorkDao;
import com.ketangpai.admin.entity.StuWork;
import com.ketangpai.admin.entity.User;
import com.ketangpai.admin.entity.UserCourse;
import com.ketangpai.admin.entity.Work;
import com.ketangpai.admin.entity.dto.StuWorkDTO;
import com.ketangpai.admin.mapper.WorkMapper;
import com.ketangpai.admin.service.UserCourseService;
import com.ketangpai.admin.service.WorkService;
import com.ketangpai.admin.dto.WorkDTO;
import com.ketangpai.admin.vo.WorkVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WorkServiceImpl implements WorkService {

    @Autowired
    private WorkMapper workMapper;
    private WorkDao workDao;
    private StuWorkDao stuWorkDao;
    private final String uploadPath = "C:/XS1/";
    private UserCourseDao userCourseDao;
    private UserDao userDao;

    public WorkServiceImpl(WorkMapper workMapper, WorkDao workDao, StuWorkDao stuWorkDao, UserCourseDao userCourseDao, UserDao userDao) {
        this.workMapper = workMapper;
        this.workDao = workDao;
        this.stuWorkDao = stuWorkDao;
        this.userCourseDao = userCourseDao;
        this.userDao = userDao;
    }

    @Override
    public WorkVO getWorkById(Integer id) {
        Work work = workMapper.selectById(id);
        if (work == null) {
            System.out.println("作业不存在");
        }
        WorkVO workVO = new WorkVO();
        BeanUtils.copyProperties(work, workVO);
        return workVO;
    }

    @Override
    public PageResult<WorkVO> getWorkList(Integer courseId, Integer status,
                                          Integer pageNum, Integer pageSize) {
        // 计算偏移量
        Integer offset = (pageNum - 1) * pageSize;

        // 查询数据
        List<Work> workList = workMapper.selectWorkList(courseId, status, offset, pageSize);
        List<WorkVO> workVOList = workList.stream().map(work -> {
            WorkVO workVO = new WorkVO();
            BeanUtils.copyProperties(work, workVO);
            return workVO;
        }).collect(Collectors.toList());

        // 查询总数
        Long total = workMapper.countWorkList(courseId, status);

        return new PageResult<>(workVOList, total, pageSize, pageNum);
    }


    @Override
    @Transactional
    public void createWork(WorkDTO workDTO) {
        Work work = new Work();
        BeanUtils.copyProperties(workDTO, work);
        work.setCreateTime(LocalDateTime.now());
        work.setStatus(workDTO.getStatus()); // 1: 未发布
        System.out.println(workDTO.getId());
        workDao.create(work);
        System.out.println(work);
        //设置stu_work表
        if(work.getStatus()==2){
            List<UserCourse> users=userCourseDao.getStudents(workDTO.getCourseId());
            for (int i=0;i<users.size();i++){

                User user=userDao.getById(users.get(i).getUserId());
                stuWorkDao.createNew(work.getId(),user.getId(),user.getName(),work.getContent());
                StuWorkDTO stuWork=stuWorkDao.queryById(work.getId(),user.getId());
                stuWork.setContent(work.getContent());
            }
        }


    }

    // WorkServiceImpl.java 中的 updateWork 方法修改
    @Override
    @Transactional
    public void updateWork(WorkDTO workDTO) {
        Work work = workMapper.selectById(workDTO.getId());
        if (work == null) {
            throw new RuntimeException("作业不存在");
        }
        if (work.getStatus() == 2) {
            throw new RuntimeException("已发布的作业不能修改");
        }

        // 如果有新文件上传，删除旧文件
        if (workDTO.getFile() != null && !workDTO.getFile().equals(work.getFile())) {
            deleteOldFile(work.getFile());
        }

        BeanUtils.copyProperties(workDTO, work);
        workMapper.update(work);
    }

    // WorkServiceImpl.java


    private void deleteOldFile(String filename) {
        if (filename != null && !filename.isEmpty()) {
            File file = new File(uploadPath + filename);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    @Override
    @Transactional
    public void deleteWork(Integer id) {
        Work work = workMapper.selectById(id);
        if (work == null) {
            System.out.println("作业不存在");
        }
        if (work.getStatus() == 2) {
            System.out.println("已发布的作业不能删除");
        }
        workMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void releaseWork(Integer id) {
        Work work = workMapper.selectById(id);
        if (work == null) {
            System.out.println("作业不存在");
        }
        if (work.getStatus() == 2) {
            System.out.println("作业已发布");
        }
        work.setStatus(2);
        work.setReleaseTime(LocalDateTime.now());
        workMapper.update(work);
    }
    @Override
    public List<com.ketangpai.admin.entity.dto.WorkDTO> queryByCid(Integer id) {
        QueryWrapper<Work> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", id);

        List<Work> workList = workDao.selectList(wrapper);

        List<com.ketangpai.admin.entity.dto.WorkDTO> workDTOList = new ArrayList<>();
        for (Work work : workList) {
            com.ketangpai.admin.entity.dto.WorkDTO workDTO = new com.ketangpai.admin.entity.dto.WorkDTO();
            BeanUtils.copyProperties(work, workDTO);
            //未交
            Integer countNoSubmit = stuWorkDao.countStatus(work.getId(), 0) + stuWorkDao.countStatus(work.getId(), 3);
            //未批改
            Integer countNoCheck = stuWorkDao.countStatus(work.getId(), 1);
            //已批改
            Integer countCheck = stuWorkDao.countStatus(work.getId(), 2);
            workDTO.setCountCheck(countCheck);
            workDTO.setCountNoCheck(countNoCheck);
            workDTO.setCountNoSubmit(countNoSubmit);
            workDTOList.add(workDTO);
        }
        return workDTOList;
    }
}
